//
//  ShenHeFinishedViewController.m
//  FactorySale
//
//  Created by 李 on 2020/3/27.
//  Copyright © 2020 主事丫环. All rights reserved.
//

#import "ShenHeFinishedViewController.h"
#import "BuZhuJinPeiJianInfoCell.h"
#import "ShenQingBuZhuJinInfoCell.h"
#import "ShenHeViewController.h"
#import "KeHuShouHuoDiZhiCell.h"
#import "HuiJiChangJiaDiZhiCell.h"
#import "BuZhuJinZheDieCell.h"
#import "GrantDetailStatesModel.h"
#import "NegotiationHistoryController.h"

#import "BalanceModel.h"
#import "IssueNowNoMoneyAlertController.h"
#import "IssueNowAlertController.h"

static NSString *const BuZhuJinZheDieCellID = @"BuZhuJinZheDieCell";
static NSString *const BuZhuJinPeiJianInfoCellID = @"BuZhuJinPeiJianInfoCell";
static NSString *const ShenQingBuZhuJinInfoCellID = @"ShenQingBuZhuJinInfoCell";
static NSString *const KeHuShouHuoDiZhiCellID = @"KeHuShouHuoDiZhiCell";
static NSString *const HuiJiChangJiaDiZhiCellID = @"HuiJiChangJiaDiZhiCell";

@interface ShenHeFinishedViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topNavBarConstraint;
//列表
@property (nonatomic,strong) GrantDetailContentModel *detailModel;
@property (weak, nonatomic) IBOutlet UILabel *timelab;
@property (weak, nonatomic) IBOutlet UITableView *listTableView;
@property (nonatomic,strong)NSMutableArray *stateListArray;
@property (nonatomic,strong)UIView *headerView;
@property (nonatomic,assign)CGFloat headerHeight;
@property (nonatomic,assign)BOOL peiJianInfoCellSelected;
@property (nonatomic,strong) GrantDetailStatesModel *statesModel;

@property (nonatomic,strong) BalanceModel *balanceModel;
@property (nonatomic,strong) UILabel *refuseLabel;
@property (nonatomic,strong) UILabel *refuseReasonLabel;
@end

@implementation ShenHeFinishedViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.topNavBarConstraint.constant = kNaviHeight;
    self.view.backgroundColor = Main_BackGroundColor;
    
    [self setupTableView];
    
    [self requestGrantsDetail];
}
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

#pragma mark - 私有方法
-(void)setupTableView {
    [self.listTableView registerClass:[BuZhuJinZheDieCell class] forCellReuseIdentifier:BuZhuJinZheDieCellID];
    [self.listTableView registerClass:[BuZhuJinPeiJianInfoCell class] forCellReuseIdentifier:BuZhuJinPeiJianInfoCellID];
    [self.listTableView registerClass:[ShenQingBuZhuJinInfoCell class] forCellReuseIdentifier:ShenQingBuZhuJinInfoCellID];
    [self.listTableView registerNib:[UINib nibWithNibName:NSStringFromClass([KeHuShouHuoDiZhiCell class]) bundle:nil] forCellReuseIdentifier:KeHuShouHuoDiZhiCellID];
    [self.listTableView registerNib:[UINib nibWithNibName:NSStringFromClass([HuiJiChangJiaDiZhiCell class]) bundle:nil] forCellReuseIdentifier:HuiJiChangJiaDiZhiCellID];
}
- (IBAction)historyButtonClick {
    NegotiationHistoryController * vc = [[NegotiationHistoryController alloc] init];
    vc.orderID = self.idStr;
    [self.navigationController pushViewController:vc animated:YES];
}
- (IBAction)backBtnClick {
    if (self.backRootController == YES) {
        [self.navigationController popToRootViewControllerAnimated:YES];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}
#pragma mark - 网络请求
-(void)requestGrantsDetail {
    NSDictionary *param = @{
        @"id":NOTNIL(self.idStr)
    };
    [NetWorkTool POST:grantsDetail param:param success:^(id dic) {
        
        self.detailModel = [GrantDetailContentModel mj_objectWithKeyValues:dic[@"data"]];
        
        self.statesModel = [GrantDetailStatesModel mj_objectWithKeyValues:dic[@"data"][@"states"]];
        
        [self refreshViewsData];
        [self.listTableView reloadData];
    } other:^(id dic) {
        ShowToastWithText(dic[@"msg"]);
        
    } fail:^(NSError *error) {
        
    } needUser:NO];
}
/**
 刷新页面
 */
-(void)refreshViewsData{
    
    if ([self.statesModel.state isEqualToString:@"-1"]) {
        self.refuseLabel.text = @"已驳回";
        NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@  商家回复：已驳回",self.statesModel.createTime]];
        NSRange range1 = [[str string] rangeOfString:self.statesModel.createTime];
        [str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHexString:@"#333333"] range:range1];
        NSRange range2 = [[str string] rangeOfString:@"商家回复：已驳回"];
        [str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHexString:@"#F2A225"] range:range2];
        self.timelab.attributedText = str;
        [self addRefuseReasonView];
        self.listTableView.frame = CGRectMake(0, 290, ScreenW, SCREEN_HEIGHT-TabbarSafeBottomMargin-290);
        self.refuseReasonLabel.text = self.statesModel.refuse;
    } else if ([self.statesModel.state isEqualToString:@"2"]){
        
        NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@  商家回复：\n已审核通过，暂未发放补助金",self.statesModel.createTime]];
        NSRange range1 = [[str string] rangeOfString:self.statesModel.createTime];
        [str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHexString:@"#333333"] range:range1];
        NSRange range2 = [[str string] rangeOfString:@"商家回复：\n已审核通过，暂未发放补助金"];
        [str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHexString:@"#F2A225"] range:range2];
        self.timelab.attributedText = str;
        [self addFooterView];
        
    } else if ([self.statesModel.state isEqualToString:@"4"]){
        NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@  师傅取消回寄",self.statesModel.createTime]];
        NSRange range1 = [[str string] rangeOfString:self.statesModel.createTime];
        [str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHexString:@"#333333"] range:range1];
        NSRange range2 = [[str string] rangeOfString:@"师傅取消回寄"];
        [str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHexString:@"#31CEA9"] range:range2];
        self.timelab.attributedText = str;
    } else if ([self.statesModel.state isEqualToString:@"5"]){
        NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@  商家回复：\n补助金已发放",self.statesModel.createTime]];
        NSRange range1 = [[str string] rangeOfString:self.statesModel.createTime];
        [str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHexString:@"#333333"] range:range1];
        NSRange range2 = [[str string] rangeOfString:@"商家回复：\n补助金已发放"];
        [str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHexString:@"#F2A225"] range:range2];
        self.timelab.attributedText = str;
    }
}
-(void)addRefuseReasonView{
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 210, SCREEN_WIDTH, 80)];
    bgView.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:bgView];
    
    UILabel *refuseTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(35, 5, 100, 30)];
    refuseTitleLabel.text = @"驳回原因";
    refuseTitleLabel.textColor = [UIColor colorWithHexString:@"#343434"];
    refuseTitleLabel.font = [UIFont systemFontOfSize:13];
    [bgView addSubview:refuseTitleLabel];
    
    UILabel *refuseLabel = [[UILabel alloc] initWithFrame:CGRectMake(35, 35, SCREEN_WIDTH-35, 40)];
    refuseLabel.text = @"";
    refuseLabel.textColor = [UIColor colorWithHexString:@"#343434"];
    refuseLabel.font = [UIFont systemFontOfSize:13];
    refuseLabel.numberOfLines = 2;
    [bgView addSubview:refuseLabel];
    self.refuseReasonLabel = refuseLabel;
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section==0) {
        if (self.peiJianInfoCellSelected ==YES) {
            return 2;
        } else {
            return 1;
        }
        return 1;
    }
    if (section==2) {
        if(self.detailModel.username.length==0||self.detailModel.userPhone.length==0||self.detailModel.userAddress.length==0) {
            return 0;
        } else {
            return 1;
        }
    }
    if (section==3) {
        if(self.detailModel.factoryName.length==0||self.detailModel.factoryPhone.length==0||self.detailModel.factoryAddress.length==0) {
            return 0;
        } else {
            return 1;
        }
        
    }
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(20, 0, SCREEN_WIDTH-40, 0.5)];
    headerView.backgroundColor = Main_BackGroundColor;
    return headerView;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section==0) {
        if (indexPath.row==0) {
            
            BuZhuJinZheDieCell *cell = [tableView dequeueReusableCellWithIdentifier:BuZhuJinZheDieCellID];
            [cell.zhanKaiBtn addTarget:self action:@selector(zhanKaiBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        } else {
            BuZhuJinPeiJianInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:BuZhuJinPeiJianInfoCellID];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            cell.model = self.detailModel;
            return cell;
        }
    }
    if (indexPath.section==1) {
        ShenQingBuZhuJinInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:ShenQingBuZhuJinInfoCellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        cell.model = self.detailModel;
        return cell;
    }
    if (indexPath.section==2) {
        KeHuShouHuoDiZhiCell *cell = [tableView dequeueReusableCellWithIdentifier:KeHuShouHuoDiZhiCellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = self.detailModel;
        return cell;
    }
    if (indexPath.section==3) {
        HuiJiChangJiaDiZhiCell *cell = [tableView dequeueReusableCellWithIdentifier:HuiJiChangJiaDiZhiCellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = self.detailModel;
        cell.arrowBtn.hidden = YES;
        return cell;
    }
    
    NSString *cellIdentifier = @"iden3";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section ==0) {
        if (indexPath.row==0) {
            return 37;
        }
        if (indexPath.row==1) {
            return 335;
        }
    }
    
    if (indexPath.section ==1) {
        return 185;
    }
    if (indexPath.section ==2) {
        return [tableView fd_heightForCellWithIdentifier:KeHuShouHuoDiZhiCellID configuration:^(KeHuShouHuoDiZhiCell * cell) {
            cell.model = self.detailModel;
        }];
    }
    if (indexPath.section ==3) {
        return [tableView fd_heightForCellWithIdentifier:HuiJiChangJiaDiZhiCellID configuration:^(HuiJiChangJiaDiZhiCell * cell) {
            cell.model = self.detailModel;
        }];
    }
    return 0;
}
-(void)zhanKaiBtnClick:(UIButton *)sender {
    sender.selected = !sender.selected;
    UIView *view = [sender superview];
    BuZhuJinZheDieCell *cell = (BuZhuJinZheDieCell *)[view superview];
    if (sender.selected) {
        self.peiJianInfoCellSelected = YES;
        [cell.zhanKaiBtn setImage:[UIImage imageNamed:@"向上"] forState:UIControlStateNormal];
    } else {
        self.peiJianInfoCellSelected = NO;
        [cell.zhanKaiBtn setImage:[UIImage imageNamed:@"向下"] forState:UIControlStateNormal];
    }
    [self.listTableView reloadData];
}
-(void)addFooterView {
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KWIDTH, 116)];
    
    UIButton *sureBut = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [sureBut setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    sureBut.frame  = CGRectMake(80, 50, KWIDTH - 160, 44);
    [sureBut setBackgroundImage:imgname(@"按钮背景") forState:UIControlStateNormal];
    [sureBut setTitle:@"立即发放" forState:UIControlStateNormal];
    [sureBut setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    sureBut.layer.masksToBounds = YES;
    sureBut.layer.cornerRadius = 22;
    [sureBut addTarget:self action:@selector(issueNowButtonClick) forControlEvents:(UIControlEventTouchUpInside)];
    [footerView addSubview: sureBut];
    
    self.listTableView.tableFooterView = footerView;
}
-(void)issueNowButtonClick{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"id"] = self.idStr;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [NetWorkTool POST:factoryAuditGrants param:param success:^(id dic) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        self.balanceModel = [BalanceModel mj_objectWithKeyValues:dic[@"data"]];
        
        if ([self.balanceModel.type isEqualToString:@"0"]) {//1可以支付 0余额不足
            // 余额不足
            IssueNowNoMoneyAlertController * vc = [[IssueNowNoMoneyAlertController alloc] init];
            vc.model = self.balanceModel;
            [self presentViewController:vc animated:YES completion:nil];
        } else {
            IssueNowAlertController * vc = [[IssueNowAlertController alloc] init];
            vc.model = self.balanceModel;
            vc.idStr = self.idStr;
            vc.okButtonClick = ^{
                [self.navigationController popToRootViewControllerAnimated:YES];
            };
            [self presentViewController:vc animated:YES completion:nil];
        }
    } other:^(id dic) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } fail:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } needUser:YES];
}

@end

